package thread;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;

import bo.IsConnected;
import bo.ListViewAdapter;
import bo.UserFunctions;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.squareup.picasso.Picasso;
import com.steam.splace.R;
import com.steam.splace.R.id;

import entity.Category;
import entity.Comment;
import entity.Message;
import entity.Place;
import entity.Region;
import entity.User;

import android.R.integer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.SubMenu;
import android.view.View;
import android.webkit.WebView.FindListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class DoThreadGet extends AsyncTask<ArrayList, ArrayList, Void> {

	private final int success_tag = 0;
	private final int viewprofile_tag = 2;
	private final int category_tag = 4;
	private final int searchplace_tag = 8;
	private final int getfavorite_tag = 9;
	private final int place_tag = 10;
	private final int getComment_tag = 11;
	private final int deleteComment_tag = 13;
	private final int region_tag = 17;
	private final int searchplacezone_tag = 18;
	private final int deleteFavorite_tag = 20;
	private static int tag = -1;
	float zoomlevel = 12;
	private String caturl = "http://cogidau.com/uploads/";
	Activity contextParent;
	ProgressDialog progress;

	public DoThreadGet(Activity ctx) {
		contextParent = ctx;
		progress = new ProgressDialog(ctx);
	}

	@Override
	protected void onPreExecute() {
		// Runs on the UI thread
		progress.setMessage("Please wait");
		progress.setIndeterminate(true);
		progress.setCancelable(false);
		progress.show();
	}

	@Override
	protected Void doInBackground(ArrayList... arg0) {
		// TODO Auto-generated method stub
		IsConnected ic = new IsConnected(contextParent);
		if (ic.isConnectedToInternet() == true) {
			UserFunctions user = new UserFunctions();
			user.setActivity(contextParent);
			if (Integer.parseInt(arg0[0].get(0).toString()) == region_tag) {
				tag = region_tag;
				ArrayList<Region> region = new ArrayList<Region>();
				region = user.getRegion();
				publishProgress(region);
			}
			if (Integer.parseInt(arg0[0].get(0).toString()) == category_tag) {
				tag = category_tag;
				ArrayList<Category> cat = new ArrayList<Category>();
				cat = user.getCategory();
				publishProgress(cat);
			}

			if (Integer.parseInt(arg0[0].get(0).toString()) == deleteFavorite_tag) {
				tag = deleteFavorite_tag;
				ArrayList favReturn = new ArrayList();
				int stt = user.deleteFavorite(Integer.parseInt(arg0[0].get(1)
						.toString()));
				favReturn.add(stt);
				favReturn.add((ListViewAdapter) arg0[0].get(2));
				favReturn.add(Integer.parseInt(arg0[0].get(3).toString()));
				publishProgress(favReturn);
			}

			if (Integer.parseInt(arg0[0].get(0).toString()) == viewprofile_tag) {
				tag = viewprofile_tag;
				ArrayList<User> tmp = new ArrayList<User>();
				tmp.add(user.getUser(Integer
						.parseInt(arg0[0].get(1).toString())));
				publishProgress(tmp);
			}/*
			if (Integer.parseInt(arg0[0].get(0).toString()) == deleteComment_tag) {
				tag = deleteComment_tag;
				user.deleteComment(Integer.parseInt(arg0[0].get(1).toString()));
				ArrayList tmp = new ArrayList();
				tmp.add(arg0[0].get(3));
				tmp.add((Comment) (arg0[0].get(2)));
				publishProgress(tmp);
			}*/
			if (Integer.parseInt(arg0[0].get(0).toString()) == getfavorite_tag) {
				tag = getfavorite_tag;
				ArrayList arr = user.getFavorite();
				arr.add(0, (Menu) arg0[0].get(2));
				publishProgress(arr);
			}
			if (Integer.parseInt(arg0[0].get(0).toString()) == getComment_tag) {
				tag = getComment_tag;
				ArrayList arr = new ArrayList();
				arr.add(user.getComment(arg0[0].get(1).toString()));
				arr.add((ArrayAdapter<Comment>) arg0[0].get(2));
				publishProgress(arr);
			}
			if (Integer.parseInt(arg0[0].get(0).toString()) == searchplace_tag) {
				tag = searchplace_tag;
				List<NameValuePair> pair = (List<NameValuePair>) arg0[0].get(1);
				ArrayList arr = new ArrayList();
				arr.add(user.searchPlace(pair));
				arr.add((GoogleMap) arg0[0].get(2));
				arr.add((HashMap<String, String>) arg0[0].get(3));
				arr.add(pair.get(1).getValue());

				publishProgress(arr);
			}
			if (Integer.parseInt(arg0[0].get(0).toString()) == searchplacezone_tag) {
				tag = searchplacezone_tag;
				List<NameValuePair> pair = (List<NameValuePair>) arg0[0].get(1);
				ArrayList arr = new ArrayList();
				arr.add(user.searchPlaceZone(pair));
				arr.add((GoogleMap) arg0[0].get(2));
				arr.add((HashMap<String, String>) arg0[0].get(3));

				publishProgress(arr);
			}
			if (Integer.parseInt(arg0[0].get(0).toString()) == place_tag) {

				tag = place_tag;
				ArrayList arr = new ArrayList();
				arr.add(user.getPlace(Integer.parseInt(arg0[0].get(1)
						.toString())));
				arr.add((GoogleMap) arg0[0].get(2));
				arr.add(user.getComment(arg0[0].get(1).toString()));
				arr.add((ArrayAdapter<Comment>) arg0[0].get(3));
				publishProgress(arr);
			}
		} else {
			ArrayList arr = new ArrayList();
			publishProgress(arr);
			tag = -404;
		}
		return null;
	}

	@Override
	protected void onProgressUpdate(ArrayList... values) {

		if (tag == category_tag) {
			ArrayList<Category> cat = (ArrayList<Category>) values[0];
			Category tmp = new Category(0, "Tất cả", "Tất cả", 0);
			cat.add(tmp);
			if (cat != null) {
				ArrayAdapter<Category> adapter = new ArrayAdapter<Category>(
						contextParent, android.R.layout.simple_spinner_item,
						cat);
				adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
				Spinner spCategory = (Spinner) contextParent
						.findViewById(R.id.spCategory);
				spCategory.setAdapter(adapter);
			}
		}
		if (tag == region_tag) {
			ArrayList<Region> region = (ArrayList<Region>) values[0];
			if (region != null) {
				ArrayAdapter<Region> adapter = new ArrayAdapter<Region>(
						contextParent, android.R.layout.simple_spinner_item,
						region);
				adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
				Spinner spRegion = (Spinner) contextParent
						.findViewById(R.id.spRegion);
				spRegion.setAdapter(adapter);
			}
		}

		if (tag == deleteFavorite_tag) {
			ArrayList region = values[0];
			ListViewAdapter lva = (ListViewAdapter) region.get(1);
			if (Integer.parseInt(region.get(0).toString()) == success_tag) {
				Toast toast = Toast.makeText(contextParent, "Xóa thành công",
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				// lva.remove(lva.getItem(Integer.parseInt(region.get(2).toString())));
				// lva.removeItemAt(Integer.parseInt(region.get(2).toString()));
				// lva.notifyDataSetChanged();
			} else {

				Toast toast = Toast.makeText(contextParent,
						"Xảy ra lỗi,vui lòng thử lại!", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}
		}
		if (tag == getfavorite_tag) {
			if (values[0] != null) {
				ArrayList<Message> arr = (ArrayList<Message>) values[0];
				Menu menu = (Menu) arr.get(0);

				SubMenu submenu = menu.addSubMenu(0, 10, 0, "Favorite");
				for (int i = 1; i < arr.size(); i++) {
					submenu.add(0, arr.get(i).getPlaceid(), i, arr.get(i)
							.getPlaceName());
					Log.v("Favorite", arr.get(i).getPlaceName());
				}
			}
		}
	/*	if (tag == deleteComment_tag) {
			ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) values[0]
					.get(0);
			adapter.remove((Comment) values[0].get(1));
		}*/
		if (tag == getComment_tag) {
			if (values[0] != null) {
				ArrayList<Comment> arr = (ArrayList<Comment>) values[0].get(0);
				/*
				 * ArrayList<String> commentContent=new ArrayList<String>();
				 * for(int i=0;i<arr.size();i++)
				 * commentContent.add(arr.get(i).toString());
				 */
				if (arr != null) {

					ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) values[0]
							.get(1);
					adapter = new ArrayAdapter<Comment>(contextParent,
							android.R.layout.simple_list_item_1, arr);
					ListView list = (ListView) contextParent
							.findViewById(R.id.listComment);
					list.setAdapter(adapter);
				}
			}
		}// c
		if (tag == searchplace_tag) {
			if (values[0] != null) {
				ArrayList searchReturn = (ArrayList) values[0].get(0);
				GoogleMap googleMap = (GoogleMap) values[0].get(1);
				HashMap<String, String> plids = (HashMap<String, String>) values[0]
						.get(2);
				googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
					@Override
					public View getInfoWindow(Marker arg0) {
						return null;
					}

					@Override
					public View getInfoContents(Marker marker) {
						View myContentView = contextParent.getLayoutInflater()
								.inflate(R.layout.custommarker, null);
						ImageView img = (ImageView) myContentView
								.findViewById(R.id.infoWindow);
						String[] s = marker.getTitle().split(";");
						// mIcon_val =
						// BitmapFactory.decodeStream(newurl.openConnection()
						// .getInputStream());

						Picasso.with(contextParent)
								.load(caturl + s[0] + ".png").into(img);
						TextView tvTitle = ((TextView) myContentView
								.findViewById(R.id.title));
						tvTitle.setText(s[1]);
						return myContentView;
					}
				});
				Place p = null;
				Marker marker;
				// int categoryID=(Integer) values[0].get(3);
				if (searchReturn != null && searchReturn.size() > 0) {
					for (int i = 0; i < searchReturn.size(); i++) {
						p = (Place) searchReturn.get(i);
						marker = googleMap.addMarker(new MarkerOptions().title(
								p.getCategoryid() + ";" + p.getPlaceName())
								.position(
										new LatLng(p.getLatitude(), p
												.getLongitude())));
						plids.put(marker.getId(), p.getPlaceid() + "");

					}
				}
				if (p != null) {
					CameraUpdate cameraUpdate = CameraUpdateFactory
							.newLatLngZoom(
									new LatLng(p.getLatitude(), p
											.getLongitude()), zoomlevel);
					googleMap.animateCamera(cameraUpdate);
				}

			}
		}
		if (tag == searchplacezone_tag) {
			if (values[0] != null) {
				ArrayList searchReturn = (ArrayList) values[0].get(0);
				GoogleMap googleMap = (GoogleMap) values[0].get(1);
				HashMap<String, String> plids = (HashMap<String, String>) values[0]
						.get(2);
				Place p = null;
				googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
					@Override
					public View getInfoWindow(Marker arg0) {
						return null;
					}

					@Override
					public View getInfoContents(Marker marker) {
						View myContentView = contextParent.getLayoutInflater()
								.inflate(R.layout.custommarker, null);
						ImageView img = (ImageView) myContentView
								.findViewById(R.id.infoWindow);
						String[] s = marker.getTitle().split(";");
						// mIcon_val =
						// BitmapFactory.decodeStream(newurl.openConnection()
						// .getInputStream());
						try {
							URL newurl = new URL(caturl + s[0] + ".png");
							Picasso.with(contextParent)
									.load(caturl + s[0] + ".png").into(img);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						TextView tvTitle = ((TextView) myContentView
								.findViewById(R.id.title));
						tvTitle.setText(s[1]);
						return myContentView;
					}
				});
				Marker marker;
				if (searchReturn != null && searchReturn.size() > 0) {
					for (int i = 0; i < searchReturn.size(); i++) {
						p = (Place) searchReturn.get(i);
						marker = googleMap.addMarker(new MarkerOptions().title(
								p.getCategoryid() + ";" + p.getPlaceName())
								.position(
										new LatLng(p.getLatitude(), p
												.getLongitude())));
						plids.put(marker.getId(), p.getPlaceid() + "");
					}
				}
				if (p != null) {
					CameraUpdate cameraUpdate = CameraUpdateFactory
							.newLatLngZoom(
									new LatLng(p.getLatitude(), p
											.getLongitude()), zoomlevel);
					googleMap.animateCamera(cameraUpdate);
				}

			}
		}
		if (tag == place_tag) {
			// load map
			TextView pName = (TextView) contextParent
					.findViewById(R.id.lbplaceName);
			TextView placeInfo = (TextView) contextParent
					.findViewById(R.id.lbplaceInfo);
			Place place = (Place) values[0].get(0);
			if (place != null) {
				GoogleMap gmaps = (GoogleMap) values[0].get(1);
				Marker marker = gmaps.addMarker(new MarkerOptions().title(
						place.getPlaceName()).position(
						new LatLng(place.getLatitude(), place.getLongitude())));
				placeInfo.setText("Mô tả:" + place.getDescription() + "\n"
						+ "Địa điểm:" + place.getAddress());
				marker.showInfoWindow();
				pName.setText(place.getPlaceName());
				CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
						new LatLng(place.getLatitude(), place.getLongitude()),
						14);
				gmaps.animateCamera(cameraUpdate);

				// load comment
				ArrayList<Comment> arr = (ArrayList<Comment>) values[0].get(2);
				/*
				 * ArrayList<String> commentContent=new ArrayList<String>();
				 * for(int i=0;i<arr.size();i++)
				 * commentContent.add(arr.get(i).toString());
				 */
				if (arr != null) {

					ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) values[0]
							.get(3);
					adapter = new ArrayAdapter<Comment>(contextParent,
							android.R.layout.simple_list_item_1, arr);
					ListView list = (ListView) contextParent
							.findViewById(R.id.listComment);
					list.setAdapter(adapter);
				}
			}
		}
		if (tag == -404) {
			Toast toast = Toast.makeText(contextParent,
					"Vui lòng kiểm tra đường truyền mạng!", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}
		if (progress.isShowing())
			progress.dismiss();
	}
	/*
	 * public static Bitmap getBitmapFromURL(String src) { try {
	 * Log.e("src",src); URL url = new URL(src); HttpURLConnection connection =
	 * (HttpURLConnection) url.openConnection(); connection.setDoInput(true);
	 * connection.connect(); InputStream input = connection.getInputStream();
	 * Bitmap myBitmap = BitmapFactory.decodeStream(input);
	 * Log.e("Bitmap","returned"); return myBitmap; } catch (IOException e) {
	 * e.printStackTrace(); Log.e("Exception",e.getMessage()); return null; } }
	 */
}
